package top.lingkang.finalgateway.core.ssl;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslContext;
import lombok.extern.slf4j.Slf4j;
import top.lingkang.finalgateway.config.RouterConfig;
import top.lingkang.finalgateway.core.DispatcherHandler;
import top.lingkang.finalgateway.core.FinalHttpObjectAggregator;

/**
 * 临时自签证书
 *
 * @author lingkang
 * Created by 2024/5/15
 */
@Slf4j
public class SslSelfSignedServerInitHandler extends ChannelInitializer<SocketChannel> {
    private final RouterConfig config;
    private final SslContext sslContext;

    public SslSelfSignedServerInitHandler(RouterConfig config, SslContext sslContext) {
        this.config = config;
        this.sslContext = sslContext;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // ssl处理
        pipeline.addLast(sslContext.newHandler(ch.alloc()));

        pipeline.addLast(new HttpServerCodec());// http编解码
        pipeline.addLast(new FinalHttpObjectAggregator(config.getMaxContentLength()));
        pipeline.addLast(new DispatcherHandler(config));
    }
}
